//
//  AsyncGETConnection.m
//  FairyDream
//
//  Created by dllo on 15/8/20.
//  Copyright (c) 2015年 dreams. All rights reserved.
//

#import "AsyncGETConnection.h"
@interface AsyncGETConnection () <NSURLConnectionDataDelegate, NSURLConnectionDelegate>
@end
@implementation AsyncGETConnection

- (void)dealloc
{
    [super dealloc];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.receiveData = [NSMutableData data];
    }
    return self;
}

+ (instancetype)asyncGETConnectionWithURL:(NSString *)URLStr pamarters:(NSDictionary *)pamarters block:(void(^)(NSData *data))messageBlock
{
    AsyncGETConnection *asy = [[AsyncGETConnection alloc] init];
    [asy startConnectionWithURL:URLStr pamarters:pamarters];
    asy.asyncBlock = messageBlock;
    return asy;
}

-(void)startConnectionWithURL:(NSString *)urlStr pamarters:(NSDictionary *)pamarters
{
    NSString *par = @"";
    for (NSString *allKey in pamarters) {
        if (par.length == 0) {
            par = [NSString stringWithFormat:@"?%@=%@", allKey, [pamarters objectForKey:allKey]];
        }
        else
        {
            par = [NSString stringWithFormat:@"%@&%@=%@", par, allKey, [pamarters objectForKey:allKey]];
        }
    }
    
    urlStr = [NSString stringWithFormat:@"%@%@", urlStr, par];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.receiveData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.asyncBlock(self.receiveData);
}


@end
